import 'dart:async';
import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/god/view/god_page.dart';
import 'package:tracker/pages/home/fence/model/fence_list_resp.dart';
import 'package:tracker/pages/home/fence/view/create_fence_page.dart';
import 'package:tracker/pages/home/fence/view/fence_page.dart';
import 'package:tracker/pages/home/flowcard/view/charge_page.dart';
import 'package:tracker/pages/home/flowcard/view/flow_card_page.dart';
import 'package:tracker/pages/home/home/view/bottom_navigator_page.dart';
import 'package:tracker/pages/home/home/view/device_info_page.dart';
import 'package:tracker/pages/home/home/view/device_list_page.dart';
import 'package:tracker/pages/home/location/view/location_page.dart';
import 'package:tracker/pages/home/mileage/view/mileage_statistics_page.dart';
import 'package:tracker/pages/home/phone_book/view/phone_book_page.dart';
import 'package:tracker/pages/home/setting/view/remote_setting_page.dart';
import 'package:tracker/pages/home/sound/view/sound_page.dart';
import 'package:tracker/pages/home/track/view/track_page.dart';
import 'package:tracker/pages/home/value_added_service/view/value_added_service_page.dart';
import 'package:tracker/pages/home/vip/enum/buy_type.dart';
import 'package:tracker/pages/home/vip/view/vip_page.dart';
import 'package:tracker/pages/home/work_mode/view/work_mode_page.dart';
import 'package:tracker/pages/login/view/agent_login_page.dart';
import 'package:tracker/pages/login/view/bind_phone_page.dart';
import 'package:tracker/pages/login/view/change_password_logon_page.dart';
import 'package:tracker/pages/login/view/change_password_page.dart';
import 'package:tracker/pages/login/view/forgot_password_page.dart';
import 'package:tracker/pages/login/view/login_page.dart';
import 'package:tracker/pages/login/view/protocol_page.dart';
import 'package:tracker/pages/login/view/reset_password_page.dart';
import 'package:tracker/pages/msg/view/msg_page.dart';
import 'package:tracker/pages/profile/view/customer_service_page.dart';
import 'package:tracker/pages/profile/view/scan_qr_code_page.dart';
import 'package:tracker/pages/profile/view/about_page.dart';
import 'package:tracker/pages/profile/view/bind_device_page.dart';
import 'package:tracker/pages/profile/view/notification_setting_page.dart';
import 'package:tracker/pages/profile/view/unbind_device_page.dart';
import 'package:tracker/pages/web/view/pay_web_view_page.dart';
import 'package:tracker/pages/home/ChangeIcon/change_icon_page.dart';
import 'package:tracker/pages/home/voice/view/secret_voice_page.dart';

import '../common/push/jpush_utils.dart';
import '../pages/home/Feedback/View/FeedbackDetail.dart';
import '../pages/home/Feedback/View/FeedbackList.dart';
import '../pages/home/Feedback/View/FeedbackSubmit.dart';
import '../pages/home/record_history/view/record_histoty_page.dart';
import '../pages/home/vip_service/view/vip_service_page.dart';
import '../startup/config/app_start.dart';



class RouterManager {
  /// 主页
  static const String home = '/';

  static const String god = '/god';

  /// 登录
  static const String login = '/login';

  /// 代理商登录
  static const String agentLogin = '/agent-login';

  /// 绑定手机
  static const String bindPhone = '/bind-phone';

  /// 用户协议
  static const String protocol = '/protocol';

  /// 忘记密码
  static const String forgotPassword = '/forgot-password';

  /// 重置密码
  static const String resetPassword = '/reset-password';

  /// 修改密码
  static const String changePassword = '/change-password';

  /// 修改密码(登录后)
  static const String changePasswordLogon = '/change-password-logon';

  /// 设备信息
  static const String deviceInfo = '/device-info';

  /// 设备列表
  static const String deviceList = '/device-list';

  /// 声音报警
  static const String sound = '/sound';

  /// 安防录音
  static const String secretVoice = '/secret-voice';

  /// 流量卡
  static const String flowCard = '/flow-card';

  /// 充值
  static const String charge = '/charge';

  /// 购买套餐
  static const String vip = '/vip';

  /// 定位
  static const String location = '/location';

  /// 轨迹
  static const String track = '/track';

  /// 远程设置
  static const String remoteSetting = '/remote-setting';

  /// 围栏
  static const String fence = '/fence';

  /// 创建围栏
  static const String createFence = '/create-fence';

  /// 里程统计
  static const String mileageStatistics = '/mileage-statistics';

  /// 电话簿
  static const String phoneBook = '/phone-book';

  /// 绑定设备
  static const String bindDevice = '/bind-device';

  /// 解绑设备
  static const String unbindDevice = '/unbind-device';

  /// 订单列表
  static const String order = '/order';

  /// 扫描二维码
  static const String scanQrCode = '/scan-qr-code';

  /// 告警设置
  static const String notificationSetting = '/notification-setting';

  /// 关于
  static const String about = '/about';

  /// 更换图标
  static const String changeIcon = '/changeIcon';

  /// 客服
  static const String customerService = '/customer-service';

  /// 网页
  static const String web = '/web';
  /// 反馈
  static const String feedback = '/feedback';
  /// 去反馈

  static const String feedbackSubmit = '/feedbackSubmit';
  static const String feedbackDetail = '/feedbackDetail';

  // vip服务
  static const String vipService = '/vipService';

  // 安防录音
  static const String recordHistory = '/recordHistory';

  //工作模式
  static const String workMode = '/workMode';

  // 消息
  static const String msg = '/msg';

  static const String valueAddedService = '/value-added-service';

  static final routerConfig = GoRouter(routes: [
    // GoRoute(name: "home", path: home, builder: (context, state) => const ChangePasswordPage(), ),
    GoRoute(
        name: "home", path: home, builder: (context, state) => const BottomNavigatorPage(), redirect: loginRedirect),
    GoRoute(
      name: "god",
      path: god,
      builder: (context, state) => const GodPage(),
    ),
    GoRoute(name: "login", path: login, builder: (context, state) => const LoginPage()),
    GoRoute(name: "agent-login", path: agentLogin, builder: (context, state) => const AgentLoginPage()),
    GoRoute(name: "bind-phone", path: bindPhone, builder: (context, state) => const BindPhonePage()),
    GoRoute(name: "forgot-password", path: forgotPassword, builder: (context, state) => const ForgotPasswordPage()),
    GoRoute(
        name: "reset-password",
        path: resetPassword,
        builder: (context, GoRouterState state) {
          XLogger.debug('reset-password :${state.uri.queryParameters}');
          final queryParameters = state.uri.queryParameters;
          String? uuid = queryParameters['uuid'];
          String? phone = queryParameters['phone'];
          return ResetPasswordPage(
            uuid: uuid!,
            phone: phone!,
          );
        }),
    GoRoute(name: "change-password", path: changePassword, builder: (context, state) => const ChangePasswordPage()),
    GoRoute(
        name: "change-password-logon",
        path: changePasswordLogon,
        builder: (context, state) => const ChangePasswordLogonPage()),
    GoRoute(
        name: "protocol",
        path: protocol,
        builder: (context, GoRouterState state) {
          String? type = state.uri.queryParameters['title'];
          String? url = state.uri.queryParameters['url'];
          return ProtocolPage(
            title: type!,
            url: url!,
          );
        }),

    /// 主页
    GoRoute(
      name: "deviceInfo",
      path: deviceInfo,
      builder: (context, state) => const DeviceInfoPage(),
    ),
    GoRoute(
      name: "deviceList",
      path: deviceList,
      builder: (context, state) => const DeviceListPage(),
    ),
    GoRoute(
        name: "sound",
        path: sound,
        builder: (context, state) {
          return const SoundPage();
        }),
      GoRoute(
      name: "secretVoice",
      path: secretVoice,
      builder: (context, state) {
      return const SecretVoicePage();
      }),
  GoRoute(
      name: "flowCard",
      path: flowCard,
      builder: (context, state) => const FlowCardPage(),
    ),
    GoRoute(
      name: "charge",
      path: charge,
      // builder: (context, state) => const ChargePage(iccid: ,),

        builder: (context, state) {

          final queryParameters = state.uri.queryParameters;
          XLogger.error(queryParameters);

          final iccid = queryParameters['iccid'] ?? "0";//int.tryParse() ?? 0;
          XLogger.error(iccid);
          return ChargePage(iccid: iccid);
        }


    ),
    GoRoute(
      name: "vip",
      path: vip,
      builder: (context, state) => const VipPage(),
    ),
    GoRoute(
      name: "valueAddedService",
      path: valueAddedService,
      builder: (context, state) {
        final buyType = state.uri.queryParameters['type'];
        return ValueAddedServicePage(
          initialBuyType: buyType != null ? BuyType.values.firstWhere((e) => e.property == buyType) : null,
        );
      },
    ),
    GoRoute(
      name: "location",
      path: location,
      builder: (context, state) => const LocationPage(),
    ),
    GoRoute(
      name: "track",
      path: track,
      builder: (context, state) => const TrackPage(),
    ),
    GoRoute(
      name: "remoteSetting",
      path: remoteSetting,
      builder: (context, state) => const RemoteSettingPage(),
    ),
    GoRoute(
      name: "fence",
      path: fence,
      builder: (context, state) => const FencePage(),
    ),
    GoRoute(
      name: "createFence",
      path: createFence,
      builder: (context, state) {
        final fenceData = state.extra as FenceData?;
        if (fenceData != null) {
          return CreateFencePage(
            fenceData: fenceData,
          );
        }
        return CreateFencePage();
      },
    ),
    GoRoute(
      name: "mileageStatistics",
      path: mileageStatistics,
      builder: (context, state) => const MileageStatisticsPage(),
    ),
    GoRoute(
      name: "phoneBook",
      path: phoneBook,
      builder: (context, state) => const PhoneBookPage(),
    ),

    /// 我的
    GoRoute(
      name: "bindDevice",
      path: bindDevice,
      builder: (context, state) => const BindDevicePage(),
    ),
    GoRoute(
      name: "unbindDevice",
      path: unbindDevice,
      builder: (context, state) => const UnbindDevicePage(),
    ),
    GoRoute(
      name: "notificationSetting",
      path: notificationSetting,
      builder: (context, state) => const NotificationSettingPage(),
    ),
    GoRoute(
      name: "customerService",
      path: customerService,
      builder: (context, state) => const CustomerServicePage(),
    ),
    GoRoute(
      name: "about",
      path: about,
      builder: (context, state) => const AboutPage(),
    ),
    GoRoute(name: "scanQrCode", path: scanQrCode, builder: (context, state) => const ScanQrCodePage()),
    GoRoute(
      name: "changeIcon",
      path: changeIcon,
      builder: (context, state) => const ChangeIconPage(),
    ),
    GoRoute(
      name: "vipService",
      path: vipService,
      builder: (context, state) {
        final queryParameters = state.uri.queryParameters;
        final chooseTabIndex = int.tryParse(queryParameters['chooseTabIndex'] ?? "0") ?? 0;
        return VipServicePage(chooseTabIndex: chooseTabIndex);
      }
    ),
    GoRoute(
      name: "recordHistory",
      path: recordHistory,
      builder: (context, state) => const RecordHistoryPage(),
    ),
    GoRoute(
      name: "workMode",
      path: workMode,
      builder: (context, state) => const WorkModePage(),
    ),
    GoRoute(
      name: "msg",
      path: msg,
      builder: (context, state) => const MsgPage(),
    ),
    GoRoute(
      name: "feedback",
      path: feedback,
      builder: (context, state) => const FeedbackListPage(),
    ),
    GoRoute(
      name: "feedbackDetail",
      path: feedbackDetail,
      builder: (context, state) {
        XLogger.info(state.uri.queryParameters);

        final queryParameters = state.uri.queryParameters;
      final feedbackId = queryParameters['feedbackId'];
      XLogger.info(feedbackId);

      return FeedbackDetailPage(
        feedbackId: int.tryParse(feedbackId ?? "") ?? 0,
        );
      }
    ),

    GoRoute(
      name: "feedbackSubmit",
      path: feedbackSubmit,
      builder: (context, state) => const FeedbackSubmitPage(),
    ),
    /// 网页
    GoRoute(
        name: "web",
        path: web,
        builder: (context, state) {
          final queryParameters = state.uri.queryParameters;
          final title = queryParameters['title'];
          final url = queryParameters['url'];
          return PayWebViewPage(
            url: url!,
            title: title,
          );
        }),
  ]);

  // 跳转到登录页面
  static FutureOr<String?> loginRedirect(BuildContext context, GoRouterState state) {
    // 判断是否同意用户协议，iOS不需要
    // XLogger.info('state.name :${state.name}');
    if (Platform.isAndroid) {
      final isAgree = SpUtil.getBool('hasAgreed') ?? false;
      XLogger.debug('isAgree :$isAgree');
      if (!isAgree) {
        return '/god';
      }
    }
    final isLogin = SpUtil.getBool('isLogin') ?? false;
    XLogger.debug('isLogin :$isLogin');
    final loggingIn = state.name == 'login';
    // 如果没登录,并且当前不在登录页面,去登录 (并将本来想要跳转的页面传递到登录页)
    if (!isLogin && !loggingIn) {
      return '/login';
    }
    return null;
  }


}
